﻿using Common;
using Newtonsoft.Json;
using NLog.LayoutRenderers;
using Seagull.BarTender.Print;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZoneLine.Common
{
    public class PrinterHelper
    {
        //private static Engine _engine = new Engine(true);

        public static void PrinterLabel(string printModePath, string printerName, Dictionary<string, string> paras, bool isPreview = false)
        {
            _ = Task.Factory.StartNew(() =>
             {
                 Logger.Log.Info($"PrinterLabel Start. printerName = {printerName}，printModePath = {printModePath}");
                 //lock (_engine)
                 using (Engine _engine = new Engine(true))
                 {
                     if (!File.Exists(printModePath))
                     {
                         throw new Exception("打印机模板文件不存在，检查");
                     }
                     // Application specific code 
                     // Explicitly start the engine 
                     _engine.Start();

                     //定义标签变量，初始化标签模板，指定打印机
                     LabelFormatDocument btFormat = _engine.Documents.Open(printModePath, printerName, printerName);

                     #region //更改打印参数
                     //指定打印机
                     // Result result = btFormat.Print("PrintJob1");
                     // Open a label format specifying a different printer 
                     //btFormat = btEngine.Documents.Open(printModePath, "OurPrinter_HX3000");

                     ////更改打印机
                     //btFormat.PrintSetup.PrinterName = @"OurPrinter_HX3000";

                     // 设置打印数量
                     // Change the number of identical labels and serialized labels to print 
                     btFormat.PrintSetup.NumberOfSerializedLabels = 1;
                     btFormat.PrintSetup.IdenticalCopiesOfLabel = 1;

                     #endregion
                     if (paras != null)
                     {
                         foreach (var item in paras)
                         {
                             //Reading Named Substrings ,读取标签字段
                             if (btFormat.SubStrings.Any(p => p.Name == item.Key))
                             {
                                 btFormat.SubStrings[item.Key].Value = item.Value;

                             }
                             //Print Label ,打印标签
                         }
                     }
                     Logger.Log.Info($"执行打印开始,打印参数:{JsonConvert.SerializeObject(paras)}");
                     Result result1 = btFormat.Print("PrintJob1");
                     Logger.Log.Info($"执行打印完成,rls={result1.ToString()},打印参数:{JsonConvert.SerializeObject(paras)}");

                     #region //五种打印方法
                     //Print Label ,Print() 直接打印btw文件 , Print(string printJobName) ,自定义打印事件名称
                     //Result result = btFormat.Print();

                     //Print Label ,Print(string printJobName, out messages) ,自定义打印事件名称
                     //Messages messages = null;
                     //Result result = btFormat.Print("PrintJob1", out messages);

                     //Print Label ,Print(string printJobName, out Messages message)

                     //Print Label ,Print(string printJobName, int waitForCompletionTimeout)

                     //Print Label ,Print(string printJobName, int waitForCompletionTimeout, out Messages messages)
                     #endregion

                     #region //打印多个模板
                     //打印多个模板
                     //int i = 0;
                     //foreach (LabelFormatDocument format in btEngine.Documents)
                     //{
                     //    i++;
                     //    format.Print("PrintJob" + i);
                     //}
                     #endregion

                     //Close Label Format ,关闭标签模板
                     btFormat.Close(SaveOptions.DoNotSaveChanges);
                     // Application-specific code 
                     // Assuming the application wants to save changes, 
                     //     it can be easily done at Stop time. 
                     //btEngine.Stop(SaveOptions.DoNotSaveChanges);

                     if (result1 == Result.Failure)
                     {
                         throw new Exception("打印失败");
                     }
                     if (result1 == Result.Timeout)
                     {
                         throw new Exception("打印超时，请检查");
                     }
                 }

                 Logger.Log.Info($"PrinterLabel Dispose. printerName = {printerName}，printModePath = {printModePath}");
             });
        }

        public static void PrinterLabelShow(string printModePath, string printerName, Dictionary<string, string> paras)
        {
            using (Engine _engineTemp = new Engine(true))
            {
                if (!File.Exists(printModePath))
                {
                    throw new Exception("打印机模板文件不存在，检查");
                }
                // Application specific code 
                // Explicitly start the engine 
                _engineTemp.Start();

                //定义标签变量，初始化标签模板，指定打印机
                LabelFormatDocument btFormat = _engineTemp.Documents.Open(printModePath, printerName);

                #region //更改打印参数
                //指定打印机
                // Result result = btFormat.Print("PrintJob1");
                // Open a label format specifying a different printer 
                //btFormat = btEngine.Documents.Open(printModePath, "OurPrinter_HX3000");

                ////更改打印机
                //btFormat.PrintSetup.PrinterName = @"OurPrinter_HX3000";

                // 设置打印数量
                // Change the number of identical labels and serialized labels to print 
                btFormat.PrintSetup.NumberOfSerializedLabels = 1;
                btFormat.PrintSetup.IdenticalCopiesOfLabel = 1;
                #endregion
                if (paras != null)
                {
                    foreach (var item in paras)
                    {
                        //Reading Named Substrings ,读取标签字段
                        if (btFormat.SubStrings.Any(p => p.Name == item.Key))
                        {
                            btFormat.SubStrings[item.Key].Value = item.Value;
                        }
                        //Print Label ,打印标签

                    }
                }

                _engineTemp.Window.VisibleWindows = VisibleWindows.InteractiveDialogs;
                var view = btFormat.PrintPreview;
                view.ShowDialog();
                #region //五种打印方法
                //Print Label ,Print() 直接打印btw文件 , Print(string printJobName) ,自定义打印事件名称
                //Result result = btFormat.Print();

                //Print Label ,Print(string printJobName, out messages) ,自定义打印事件名称
                //Messages messages = null;
                //Result result = btFormat.Print("PrintJob1", out messages);

                //Print Label ,Print(string printJobName, out Messages message)

                //Print Label ,Print(string printJobName, int waitForCompletionTimeout)

                //Print Label ,Print(string printJobName, int waitForCompletionTimeout, out Messages messages)
                #endregion

                #region //打印多个模板
                //打印多个模板
                //int i = 0;
                //foreach (LabelFormatDocument format in btEngine.Documents)
                //{
                //    i++;
                //    format.Print("PrintJob" + i);
                //}
                #endregion

                //Close Label Format ,关闭标签模板
                btFormat.Close(SaveOptions.DoNotSaveChanges);
                // Application-specific code 
                // Assuming the application wants to save changes, 
                //     it can be easily done at Stop time. 
                //btEngine.Stop(SaveOptions.DoNotSaveChanges);
            }
        }
    }
}
